<template>
  <div>
    <div
      v-show="messageList.length"
      class="bg_fff messbox"
      :class="{ noborder: !hasborder }"
    >
      <div
        v-for="(item, index) in messageList"
        :key="index"
        class=""
        :class="{'timebox':hasTime}"
      > 
        <!-- 时间 -->
        <div v-if="hasTime" class="chatinterval flex p-8 f-14">
          <template v-if="typeTime===0">
            <el-input size="mini" v-model="item.timenum" style="width:65px" class="mr-8" />
            <el-select size="mini" v-model="item.until" placeholder="" style="width:80px">
              <el-option label="秒" :value="1"></el-option>
              <el-option label="分钟" :value="2"></el-option>
              <el-option label="小时" :value="3"></el-option>
            </el-select>
            <span class="pl-10">
              <span v-if="index!==0">上一条消息发送后</span>
              {{item.timenum}}  
              <span v-if="item.until==1">秒</span>
              <span v-if="item.until==2">分钟</span>
              <span v-if="item.until==3">小时</span>
              后发送</span>
            </template>
            <template v-else>
              <el-time-picker
                size="mini"
                v-model="item.time"
                value-format='HH:mm:ss'
                placeholder="选择时间"
                style="width:120px">
              </el-time-picker>
            </template>
        </div>
        <div class="flexbetween messageitem p-10">
          <div class="flex aligncenter">
            <div v-if="leftType == 1">
              <div v-if="slotExists('itemleft')">
                <slot name="itemleft"></slot>
              </div>
              <div v-else class="numberindex ml-12 mr-12">{{ index + 1 }}</div>
            </div>
            <div v-if="leftType == 2">
              <el-checkbox
                v-model="item.checked"
                style="margin: 0px 16px 0px 6px"
              >
                <span class="c_text"></span>
              </el-checkbox>
            </div>
            <!-- 文字 -->
            <div v-if="item.type == 'text'" class="m_textbox c_000">
              {{ item.contentJson || "" }}
            </div>
            <div v-else-if="item.type == 'img'">
              <img :src="item.img" alt="" class="m_imgbox" />
            </div>
          </div>
          <div class="flex mr-8 button-list">
            <!-- <i class="el-icon-plus"></i> -->
            <!-- 添加 -->
            <el-popover class="item" trigger="click" effect="light" placement="top-end">
              <div class="flex">
                <div v-for="(item, index) in typeList" :key="index" class="mr-8">
                  <el-button size="small" class="btn_item" @click="handleTypeOpen(item,index)">
                    {{ item.name }}
                    <input
                      v-if="item.id == 2 || item.id == 3 || item.id == 4"
                      type="file"
                      :id="'photo' + index"
                      class="filebtn"
                      :accept="item.accept"
                      @change="chooseUpload($event, item, index)"
                    />
                    <el-tooltip
                      class="item"
                      effect="dark"
                      popper-class="btntooltip"
                      :content="item.info"
                      placement="top-start"
                    >
                      <i v-if="item.info" class="el-icon-info"></i>
                    </el-tooltip>
                  </el-button>
                </div>
              </div>
              <div slot="reference" class="m_btn flexcenter commhover">
                <i class="el-icon-plus"></i>
              </div>
            </el-popover>
            <div class="m_btn ml-8 flexcenter commhover" @click="handleEdit(item, index)">
              <i class="el-icon-edit"></i>
            </div>
            <div
              class="m_btn flexcenter commhover"
              @click="handleDelete(item, index)"
            >
              <i class="el-icon-delete"></i>
            </div>
            <template v-if="removeIcon">
              <div class="m_line commhover"></div>
              <div
                v-if="index !== messageList.length - 1"
                class="m_btn flexcenter commhover"
                @click="handleDown(index)"
              >
                <i class="el-icon-download"></i>
              </div>
              <div
                v-if="index !== messageList.length - 1"
                class="m_btn flexcenter commhover"
                @click="handleMoveDown(index)"
              >
                <i class="el-icon-arrow-down"></i>
              </div>
              <div
                v-if="index !== 0"
                class="m_btn flexcenter commhover"
                @click="handleMoveTop(index)"
              >
                <i class="el-icon-arrow-up"></i>
              </div>
              <div
                v-if="index !== 0"
                class="m_btn flexcenter commhover"
                @click="handleTop(index)"
              >
                <i class="el-icon-upload2"></i>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div v-if="showTool" class="flex aligncenter toolbox">
      <span class="mr-8">{{ messageList.length }}/{{ maxlength }}</span>
      <div v-for="(item, index) in typeList" :key="index" class="mr-8">
        <el-button size="small" class="btn_item" @click="handleTypeOpen(item)">
          {{ item.name }}
          <input
            v-if="item.id == 2 || item.id == 3 || item.id == 4"
            type="file"
            :id="'photo' + index"
            class="filebtn"
            :accept="item.accept"
            @change="chooseUpload($event, item, index)"
          />
          <el-tooltip
            class="item"
            effect="dark"
            popper-class="btntooltip"
            :content="item.info"
            placement="top-start"
          >
            <i v-if="item.info" class="el-icon-info"></i>
          </el-tooltip>
        </el-button>
      </div>
    </div>
    <!-- 文本 -->
    <reply-text
      v-if="opentext"
      :visable="opentext"
      :title="replytitle"
      :selectItem="selectItem"
      @submit="addSubmit"
      @close="handleReplyClose"
    />
    <!-- 链接 -->
    <reply-link
      v-if="openlink"
      :visable.sync="openlink"
      :title="replytitle"
      :selectItem="selectItem"
      @submit="addSubmit"
      @close="handleReplyClose"
    />
    <!-- 素材库 -->
    <reply-material
      v-if="openmaterial"
      :visable="openmaterial"
      :type="opentype"
      title="从素材库导入"
      :selectItem="selectItem"
      @submit="addSubmit"
      @close="handleReplyClose"
    />
  </div>
</template>
<script>
import ReplyText from "./ReplyText.vue";
import ReplyLink from "./ReplyLink.vue";
import ReplyMaterial from "./ReplyMaterial.vue";
import { isOverSize } from '@/utils/validate';
export default {
  data() {
    return {
      typeList: [
        { id: 1, name: "文字", type: "text" },
        { id: 2, name: "图片", type: "img", accept: "image/*" },
        {
          id: 3,
          name: "视频",
          type: "video",
          accept: "video/*",
          info: "发送视频传送比较耗时，如果发送消息间隔设置又较短，可能会出现消息乱序，所以视频尽量压缩小一点",
        },
        { id: 4, name: "文件", type: "file", accept: "" },
        { id: 5, name: "链接", type: "link" },
        { id: 6, name: "小程序", type: "program" },
        { id: 7, name: "视频号", type: "videoplus" },
        { id: 8, name: "表情", type: "emjoy" },
        {
          id: 9,
          name: "素材库",
          type: "material",
          info: "素材库支持小程序、视频号的素材形式",
        },
      ],
      messageList: [],
      opentext: false,
      replytitle: "",
      selectItem: null,
      opentype: "",
      openlink: false,
      openmaterial: false,
      rowindex:'',
      isEdit: false,//是否是编辑
      typeTime:0,//0 为时间段随机发送  1为时间点精确发送
    };
  },
  components: {
    ReplyText,
    ReplyLink,
    ReplyMaterial
  },
  props: {
    value: {
      type: Array,
    },
    maxlength: {
      type: Number,
      default: 100,
    },
    showTool: {
      //是否展示底部工具栏
      type: Boolean,
      default: true,
    },
    hasborder: {
      //是否需要边框
      type: Boolean,
      default: true,
    },
    leftType: {
      type: Number,
      default: 1,
    },
    removeIcon:{ //移动icon
      type: Boolean,
      default:true
    },
    hasTime:{ //是否展示时间
      type: Boolean,
      default:false
    },
    defaultTime:{
      type:Number,
      default:10
    },
    timeType:{
      type:Number,
      default:0,//0 为时间段随机发送  1为时间点精确发送
    },
  },
  watch: {
    value: {
      handler(val) {
        if (val) this.messageList = val;
      },
      immediate: true,
      deep: true,
    },

    timeType:{
      handler(val) {
        this.typeTime = val;
      },
      immediate: true,
      deep: true,
    }
  },
  methods: {
    // 判断是否有slot
    slotExists(slotName) {
      return !!this.$slots[slotName];
    },

    handleTypeOpen(item, index='') {
      this.isEdit = false
      if (this.messageList.length >= this.maxlength) {
        this.$message.warning("最多创建" + this.maxlength + "条内容");
        return;
      }
      this.opentype = item.type;
      this.rowindex = index
      switch (item.type) {
        case "text":
          this.opentext = true;
          this.replytitle = "添加文字";
          break;
        case "link":
          this.openlink = true;
          this.replytitle = "添加链接";
          break;
        case "program":
        case "videoplus":
        case "material":
          this.openmaterial = true;
          break;
        default:
          break;
      }
    },

    addSubmit(text) {
      if(this.isEdit){
        this.handleEditSubmit(text)
        return
      }
      switch (this.opentype) {
        case "text":
          let item = {
            type: "text",
            contentType: "text",
            contentJson: text,
            contentOrderIndex: this.messageList.length + 1,
          }
          if(this.hasTime){
            item.timenum = 10
            item.until = 1
          }
          if(this.rowindex||this.rowindex===0){
            this.messageList.splice(this.rowindex+1, 0, item);
          }else{
            this.messageList.push(item);
          }
          break;
      }
      // if (this.selectItem) {
      //   //编辑的
      //   this.selectItem.message = text;
      // } else {
      //   //添加的
      //   this.messageList.push({ type: 1, message: text });
      // }

      this.handleReplyClose(this.opentype);
    },

    // 编辑
    handleEditSubmit(text){
      switch (this.opentype) {
        case "text":
          let item =  Object.assign({},this.selectItem,{contentJson: text})
          // if(this.rowindex||this.rowindex===0){
          //   this.messageList.splice(this.rowindex+1, 0, item);
          // }else{
          //   this.messageList.push(item);
          // }
          this.messageList.splice(this.rowindex, 1, item)
          break;
      }
      this.handleReplyClose(this.opentype);
    },

    handleReplyClose(type) {
      switch (type) {
        case "text":
          this.opentext = false;
          this.selectItem = null;
          break;
        case "link":
          this.openlink = false;
          this.selectItem = null;
          break;
        case "program":
        case "videoplus":
        case "material":
          this.openmaterial = false;
          this.selectItem = null;
        default:
          break;
      }
    },

    chooseUpload(event, item, index) {
      var file = event.currentTarget.files[0];
      if (isOverSize(file.size, 5)) {
        this.$message.warning("大小不能超过5MB");
        return;
      }
      console.log(file);
      //   var formData = new FormData();
      //   formData.append("file", file);
      //   formData.append("uid",localStorage.getItem('uid'));
      //   post("upload/Img", formData).then((response) => {
      //     if (response.code == 1) {
      //       if (num == 1) {
      //         item.pageData.imgurl = response.data;
      //         document.getElementById("pageData" + index).value = null;
      //       } else {
      //         item.images = response.data;
      //         document.getElementById("photo"+ index).value = null;
      //       }
      //       this.$message({
      //         duration: 800,
      //         message: "上传成功",
      //         type: "success",
      //       });
      //     } else {
      //       this.$message.error(response.msg);
      //     }
      //   });
    },

    handleDelete(item, index) {
      this.messageList.splice(index, 1);
    },

    handleEdit(item, index) {
      this.isEdit = true
      this.rowindex = index
      this.opentype = item.type;
      if (item.type == 'text') {
        this.selectItem = item;
        this.opentext = true;
        this.replytitle = "编辑文字";
      }
    },

    // 下移
    handleMoveDown(index) {
      let arr = this.messageList;
      arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    },
    // 上移
    handleMoveTop(index) {
      let arr = this.messageList;
      arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    },

    // 置底
    handleDown(index) {
      let arr = this.messageList;
      arr.push(arr.splice(index, 1)[0]);
    },
    // 置顶
    handleTop(index) {
      let arr = this.messageList;
      arr.unshift(arr.splice(index, 1)[0]);
    },
  },
};
</script>
<style lang="scss" scoped>
.messbox {
  border: 1px solid #e9e9e9;
  border-bottom: none;
  &.noborder {
    border: 0;
  }
}
.timebox{
  margin-bottom: 8px;
  .messageitem{
    border: 1px solid #e9e9e9;
  }
}
.chatinterval{
  background: #f5f5f5;
  border: 1px solid #e9e9e9;
  border-bottom: 0;
  line-height: 24px;
}
.messageitem {
  min-height: 60px;
  &:hover {
    background-color: #f5f5f5;
    .button-list {
      display: flex;
    }
  }
  .button-list {
    display: none;
    .flexcenter {
      background: #ffffff;
      &:hover {
        background: #2f54eb;
        color: #ffffff;
      }
      &:not(:last-child) {
        margin-right: 8px;
      }
    }
  }
}
.toolbox {
  min-height: 47px;
  padding: 8px 16px;
  background: #f7f7f7;
  border: 1px solid #e9e9e9;
}
.m_btn {
  height: 28px !important;
  width: 28px !important;
  border: 1px solid #e9e9e9;
  padding: 0 !important;
  line-height: 28px;
  border-radius: 4px;
}
.m_line {
  width: 1px;
  background: #e9e9e9;
  height: 20px;
  margin: 4px 16px 4px 8px;
}
.m_imgbox {
  max-width: 160px;
  max-height: 160px;
  border-radius: 5px;
}
.btn_item {
  padding: 0 7px;
  height: 26px !important;
  font-size: 14px !important;
  overflow: hidden;
  position: relative;

  .filebtn {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    opacity: 0;
  }
}
.numberindex {
  width: 20px;
  height: 20px;
  line-height: 20px;
  font-size: 12px;
  background: #ddd;
  border-radius: 50%;
  display: inline-block;
  text-align: center;
}
.m_textbox {
  background: #fff;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
  padding: 6px 12px;
  max-width: 360px;
  word-break: break-all;
}

</style>
